<template>
  <div>
    <el-image :src="value" class="img-box" :preview-src-list="[value]">
      <div slot="error" class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image>

    <el-button type="primary" plain @click="handleClick">扫描</el-button>
    <div class="take" v-if="show">
      <video ref="video" autoplay class="video1"></video>
      <div class="tool">
        <el-button type="primary" plain @click="takePhoto('111')"
          >拍照</el-button
        >
        <el-button type="primary" plain @click="submitImg">确定</el-button>
        <el-button type="primary" plain @click="show = false">取消</el-button>
      </div>

      <canvas ref="canvas"></canvas>
    </div>
  </div>
</template>

<script>
import api from "@/api/api";
export default {
  props: {
    value: {
      type: [String],
      default: "",
    },
  },
  data() {
    return {
      show: false,
    };
  },
  computed: {
    inputValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },
  },
  created() {},
  mounted() {
    // this.startCamera();
  },
  watch: {
    show(newVal, oldVal) {
      // watch可以监听一些状态发生更改的时候，做一些处理，修改状态，或者异步操作

      console.log(1);
    },
  },
  methods: {
    base64ToFile(urlData, fileName) {
      let arr = urlData.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]);
      let n = bytes.length;
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
    async submitImg() {
      let param = new FormData();
      const canvas = this.$refs.canvas;
      param.append(
        "file",
        this.base64ToFile(
          canvas.toDataURL("image/png"),
          `${this.currentBatch}.png`
        )
      );
      param.append("user_name", "mason");

      // 注意添加headers
      let url = await api.upload(param);
      this.inputValue = url;
      console.log(this.inputValue);
      this.show = false;

      // await api.add({ batch: this.currentBatch, img: url });
      // this.inputChange();
    },

    handleClick() {
      this.show = true;
      this.startCamera();
    },
    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        });
        this.$refs.video.srcObject = stream;
      } catch (error) {
        console.error("Error accessing the camera:", error);
      }
    },
    takePhoto(batch) {
      console.log(batch);
      this.currentBatch = batch;
      this.dialogVisible = true;
      this.$nextTick(() => {
        const video = this.$refs.video;
        const canvas = this.$refs.canvas;
        const context = canvas.getContext("2d");

        // const widthMax = 800;
        // const heihtMax = 1200;

        // canvas.width =
        //   video.videoWidth > widthMax ? widthMax : video.videoWidth;
        // canvas.height =
        //   video.videoHeight > heihtMax ? heihtMax : video.videoHeight;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        context.font = "50px serif";
        context.fillStyle = "#FFF000";
        context.fillText(batch, 10, 50);
        this.dialogWidth = canvas.width + "px";
        this.$message(`${canvas.width}${canvas.height}`);
        this.imgCanvas = canvas;
      });
    },
  },
  components: {},
};
</script>

<style scoped lang="scss">
.img-box {
  width: 50px;
  height: 50px;
}
.take {
  background-color: aliceblue;
  display: flex;
  width: 1000px;
  height: 800px;
  border: 1px solid;

  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
}
video {
  max-width: 500px;
  max-height: 800px;
}
.tool {
  background-color: bisque;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.el-button + .el-button {
  margin-left: 0px;
}
</style>
